﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace Evaluant.Uss.Linq
{
    public class EussQueryProvider : IQueryProvider
    {
        public ObjectContext.ObjectContext ObjectContext { get; set; }
        public List<string> InferredRelationships { get; set; }
        public bool DetachResult { get; set; }

        public EussQueryProvider(ObjectContext.ObjectContext oc)
        {
            this.ObjectContext = oc;
            this.InferredRelationships = new List<string>();
            this.DetachResult = false;
        }

        public IQueryable CreateQuery(Expression expression)
        {
            Type elementType = TypeSystem.GetElementType(expression.Type);
            try
            {
                return (IQueryable)Activator.CreateInstance(typeof(QueryableEussData<>).MakeGenericType(elementType), new object[] { this, expression });
            }
            catch (System.Reflection.TargetInvocationException tie)
            {
                throw tie.InnerException;
            }
        }

        // Queryable's collection-returning standard query operators call this method.
        public IQueryable<TResult> CreateQuery<TResult>(Expression expression)
        {
            return new QueryableEussData<TResult>(this, expression);
        }

        public object Execute(Expression expression)
        {
            throw new NotImplementedException();
        }

        // Queryable's "single value" standard query operators call this method.
        // It is also called from QueryableTerraServerData.GetEnumerator().
        public TResult Execute<TResult>(Expression expression)
        {
            return (TResult) new EussQueryContext().Execute<TResult>(expression, ObjectContext);
        }

    }
}
